package com.chookss.home.logContacts;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.LogManagerEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.Nullable;

@SuppressLint("ValidFragment")
public class LogGroupFragment extends Fragment implements OnRefreshListener, OnLoadMoreListener {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.logscl)
    ConsecutiveScrollerLayout logscl;
    @BindView(R.id.logNoneTv)
    TextView logNoneTv;
    private LogGroupsAdapter adapter;
    private List<LogManagerEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String type;//0全部日志1我的日志
    private String reportType = "";// 0 日报 1 周报 2 月报 3 日志
    private String startTime = "", endTime = "";
    private String employeeCodes = "", orgCodes = "";//筛选的组织和人
    private BottomListsDialog bottomListsDialog = null;

    public LogGroupFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_log, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        //注册接受
        EventBus.getDefault().register(this);
        logscl.setBackgroundColor(getResources().getColor(R.color.main_bg));
        logNoneTv.setText("暂无分组");
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new LogGroupsAdapter(R.layout.item_log_group, mContext, list);
        rv.setAdapter(adapter);
        getData();
    }

    private RefreshLayout refreshLayout;
    private boolean isFirst = false;

    @Override
    public void onRefresh(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        isEnd = false;
        currentPage = 1;
        getData();
    }

    @Override
    public void onLoadMore(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        if (isEnd) {//has next page
            MyToast.show("没有更多数据了");
            loadEnd();
        } else {
            currentPage++;
            getData();
        }
    }
    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<LogManagerEntity>>>() {
        }.getType(), null, Urls.selectReportTeamList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<LogManagerEntity>>() {
            @Override
            public void onSuccess(List<LogManagerEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (rv==null||llNone==null) {
                    return;
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex, data.size());
                    rv.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        rv.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();

            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }


    private void loadEnd() {
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh(true);
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore(true);
    }
    class LogGroupsAdapter extends BaseQuickAdapter<LogManagerEntity, BaseViewHolderEx> {
        private Context context;

        public LogGroupsAdapter(int layoutResId, Context context, @Nullable List<LogManagerEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, LogManagerEntity item) {
            TextView tvType = helper.getView(R.id.tvType);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvInit = helper.getView(R.id.tvInit);
            RelativeLayout rlMore = helper.getView(R.id.rlMore);
            tvTitle.setText(item.getTeamName());
            if("0".equals(item.getReportType())){
                tvType.setText("日报");
            }else if("1".equals(item.getReportType())){
                tvType.setText("周报");
            }else if("2".equals(item.getReportType())){
                tvType.setText("月报");
            }else if("3".equals(item.getReportType())){
                tvType.setText("日志");
            }else{
                tvType.setText("分组");
            }
            tvInit.setText("成员共"+item.getEmpNum()+"人");
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, LogGroupsActivity.class);
                    intent.putExtra("teamCode", item.getTeamCode());
                    intent.putExtra("teamName", item.getTeamName());
                    intent.putExtra("owerEmployeeCode", item.getOwerEmployeeCode());
                    intent.putExtra("reportType", item.getReportType());
                    startActivity(intent);
                }
            });
            rlMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, LogManagerEditActivity.class);
                    intent.putExtra("id", item.getId());
                    startActivity(intent);
                }
            });
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("RefreshLogMangerFragment".equals(msg)) {
                //刷新最近列表
                isEnd = false;
                currentPage = 1;
                getData();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();

    }

}
